import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/lget/lget.dart';
import 'package:liuxlcommon/view/extension_widget.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_style.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/view/common_view.dart';
import 'package:ladder_cash/app/page/index/index_page.dart';
import 'package:ladder_cash/app/page/mine/mine_page.dart';
import 'package:ladder_cash/app/page/order/order_logic.dart';
import 'package:ladder_cash/app/page/order/order_page.dart';
import 'package:ladder_cash/value/app_colors.dart';
import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:liuxlcommon/util/toast_util.dart';

import '../../../gen/assets.gen.dart';
import '../../../library/src/logger.dart';
import '../../com/plugin/common_plugin.dart';
import '../login/login_page.dart';
import 'home_logic.dart';

class HomePage extends StatefulWidget {
  HomePage({super.key});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with RouteAware {
  final logic = Get.put(HomeLogic());
  late final List<Widget> pglist;
  @override
  void initState() {
    super.initState();
    pglist = [
      const IndexPage(),
      OrderPage(),
      MinePage(changeIndex:callback),
    ]; //OrderPage(),
  }

  /// 向子组件暴露方法切换index;
  void callback(int index) {
    nitemclick(index);
  }



  var tabImages = [
    [
      getTabImage(Assets.tab.homeChecked.path),
      getTabImage(Assets.tab.home.path)
    ],
    [
      getTabImage(Assets.tab.orderChecked.path),
      getTabImage(Assets.tab.order.path),
    ],
    [
      getTabImage(Assets.tab.meChecked.path),
      getTabImage(Assets.tab.me.path),
    ],
  ];
  // get tabNames => App.localeEn?  ["Home","Order", "Me"]: ["Hogar","Orden", "A mí"]; //

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    App.routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    // precacheImage(const AssetImage(Assets.bPinjamSy3), context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: AppColors.bgColor,
      body: GetBuilder<HomeLogic>(
        builder: (s) => doubleExit(
            child: Stack(
          children: [
            LContainer(
                lStyle:
                    LStyle(width: double.infinity, height: double.infinity)),
            Column(
              children: [LExpand(child: pageView), bottomBar],
            )
          ],
        )),
      ),
    );
  }

  get bottomBar => GetBuilder<HomeLogic>(
        id: 'bottom',
        builder: (l) => LRow(
            lStyle: LStyle(
                backgroundColor: Colors.white,
                // padding: EdgeInsets.symmetric(horizontal: 50.w),
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.w),
                    topRight: Radius.circular(20.w)),
                boxShadow: [
                  BoxShadow(
                      color: 0xFFE8E8E8.color,
                      offset: Offset(0, 4.w),
                      blurRadius: 15.w)
                ]),
            children: List.generate(pglist.length, (index) => tabItem(index))),
      );

  get pageView => PageView(
        physics: const NeverScrollableScrollPhysics(),
        controller: logic.pageController,
        onPageChanged: (position) {
          logic.mapHomeListener.forEach((key, value) {
            value.onHomePageChanged(position);
          });
        },
        children: List.generate(pglist.length, (index) => pglist[index]),
      );

  Widget tabItem(index) {
    return LContainer(
        lStyle: LStyle(
            height: 48.w + LGet.bottomPadding(context),
            flex: 1,
            alignment: Alignment.center),
        child: getTabIcon(index),
        onTap: () => nitemclick(index));
  }

  getTabIcon(int curIndex) {
    Image image = curIndex == logic.currentIndex
        ? tabImages[curIndex][0]
        : tabImages[curIndex][1];
    return image;
  }

  int onclickTime = 0;
  int count = 0;

  nitemclick(index) async {
    if (index != 0 && !App.isLogin()) {
      Get.to(LoginPage());
      return;
    }
    if(index == 0){
      CommonPlugin.initAdjust;
    }

    logic.pageController.jumpToPage(index);
    logic.currentIndex = index;
    setState(() {});

    int currTime = DateTime.now().millisecondsSinceEpoch;
    if (currTime - onclickTime < 300 || onclickTime == 0) {
      count++;
      onclickTime = currTime;
      if (count > 9) {
        HttpRequest.isProxy = !HttpRequest.isProxy;
        ToastUtils.toast(HttpRequest.isProxy.toString());
        count = 0;
      }
    } else {
      onclickTime = currTime;
      count = 0;
    }
  }

  @override
  void dispose() {
    // Get.delete<HomeLogic>();
    App.routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {}

  @override
  void didPop() {}

  @override
  void didPopNext() {
    logic.mapHomeListener.forEach((key, value) {
      value.onHomePageChanged(logic.currentIndex);
    });
  }

  @override
  void didPushNext() {}
}

Image getTabImage(String path) {
  return Image.asset(path, width: 20.w, height: 19.w);
}
